import {useEffect, useRef} from "react";
import * as echarts from "echarts";


const BarCharts = ({xData, yData, title, onWidth, onHeight, barWidth, onColor}) => {
    const chartRef = useRef(null);
    // 页面渲染完成后执行
    useEffect(() => {
        // 保证dom可用，在进行图表渲染
        // 1. 链接dom节点
        // 2. 初始化echarts实例
        const myChart = echarts.init(chartRef.current);
        // 3. 准备图标参数
        const option = {
            title: {
                text: title
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                //坐标轴斜着显示
                axisLabel: {
                    interval: 0,
                    rotate: 40,
                    color: "#182ba9",
                    fontSize: 16
                },
                axisTick: {
                    alignWithLabel: true
                },
                data: xData
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: yData,
                    name: 'Direct',
                    type: 'bar',
                    barWidth: barWidth,
                    itemStyle: {
                        // 柱形图圆角
                        borderRadius: [3, 3, 0, 0],
                        color: onColor
                    }
                }
            ]
        }
        // 4. 使用图表配置项渲染图表
        option && myChart.setOption(option);
    }, [])

    return (
        <div ref={chartRef} style={{width: onWidth, height: onHeight}}></div>
    )
}

export default BarCharts